import React, { useState, useEffect } from 'react';
import './Countdown.css'; // 引入样式文件

const Countdown = () => {
    // 从 sessionStorage 获取 stopTimestamp（单位为毫秒）
    const stopTimestamp = parseInt(sessionStorage.getItem('stopTimestamp'), 10);
    const currentTime = Date.now();

    // 计算剩余时间（单位为秒）
    const initialTimeLeft = Math.max(0, Math.floor((stopTimestamp - currentTime) / 1000));

    const [timeLeft, setTimeLeft] = useState(initialTimeLeft); // 初始时间，单位为秒

    useEffect(() => {
        // 如果时间已经结束，直接返回
        if (timeLeft <= 0) return;

        const interval = setInterval(() => {
            setTimeLeft(prevTime => {
                if (prevTime > 0) {
                    return prevTime - 1; // 每秒减少1
                } else {
                    clearInterval(interval); // 清理定时器
                    return 0;
                }
            });
        }, 1000);

        return () => clearInterval(interval); // 清理定时器
    }, [timeLeft]);

    const formatTime = (seconds) => {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = seconds % 60;
        return {
            hours: String(hours).padStart(2, '0'),
            minutes: String(minutes).padStart(2, '0'),
            seconds: String(secs).padStart(2, '0'),
        };
    };

    const { hours, minutes, seconds } = formatTime(timeLeft);

    return (
        <div className="countdown">
            <div className="time">
                <div className="number">{hours}</div>:
                <div className="number">{minutes}</div>:
                <div className="number">{seconds}</div>
            </div>
            {timeLeft <= 0 && <div className="finished">考试已结束</div>}
        </div>
    );
};

export default Countdown;
